#!/bin/bash

APP=gmall

# 如果是输入的日期按照取输入日期；如果没输入日期取当前时间的前一天
if [ -n "$2" ] ;then
    do_date=$2
else
    do_date=`date -d "-1 day" +%F`
fi

common_sql="use ${APP};"

dws_trade_user_order_td_sql="
    with yesterday as (
        select
            user_id,
            order_date_first,
            order_date_last,
            order_count_td,
            order_num_td,
            original_amount_td,
            activity_reduce_amount_td,
            coupon_reduce_amount_td,
            total_amount_td
        from dws_trade_user_order_td
        where dt = date_sub('${do_date}', 1)
    ), today as (
        select
            user_id,
            '${do_date}',
            '${do_date}',
            order_count_1d,
            order_num_1d,
            order_original_amount_1d,
            activity_reduce_amount_1d,
            coupon_reduce_amount_1d,
            order_total_amount_1d
        from dws_trade_user_order_1d
        where dt = '${do_date}'
    ), full_result as (
        select * from yesterday
        union
        select * from today
    )
    insert overwrite table dws_trade_user_order_td partition (dt = '${do_date}')
    select
        user_id,
        min(order_date_first) as order_date_first,
        max(order_date_last) as order_date_last,
        sum(order_count_td) as order_count_td,
        sum(order_num_td) as order_num_td,
        sum(original_amount_td) as original_amount_td,
        sum(activity_reduce_amount_td) as activity_reduce_amount_td,
        sum(coupon_reduce_amount_td) as coupon_reduce_amount_td,
        sum(total_amount_td) as total_amount_td
    from full_result
    group by user_id;
"

dws_user_user_login_td_sql="
    with yesterday as (
        select
            user_id,
            login_last_date,
            login_count_td
        from dws_user_user_login_td
        where dt = date_sub('${do_date}', 1)
    ), today as (
        select
            user_id,
            date_id,
            1
        from dwd_user_login_inc
        where dt = '${do_date}'
    ), full_result as (
        select * from yesterday
        union
        select * from today
    )
    insert overwrite table dws_user_user_login_td partition (dt = '${do_date}')
    select
        user_id,
        max(login_last_date),
        sum(login_count_td)
    from full_result
    group by user_id;
"

# 判断表名参数，表名参数是第一个参数
case $1 in
"dws_trade_user_order_td")
    hive -e "${common_sql}${dws_trade_user_order_td_sql}"
;;
"dws_user_user_login_td")
    hive -e "${common_sql}${dws_user_user_login_td_sql}"
;;
"all")
    hive -e "${common_sql}${dws_trade_user_order_td_sql}${dws_user_user_login_td_sql}"
;;
esac